<?php

class Helper_Util {
	/**
	 * add_dl_header
	 *
	 * 添加下载文件的header
	 * $filename 文件名
	 */
	public static function add_dl_header($filename) {
		header ( "Content-Type: application/octet-stream" );
		header ( 'Content-Disposition: attachment; filename="' . iconv ( "utf-8", "gb2312", $filename ) . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
	}
	
	/**
	 * cannot_null
	 *
	 * 验证字段不能为空
	 */
	public static function cannot_null($info) {
		$flag = true;
		if ($info == null || $info === "") {
			$flag = false;
		}
		return $flag;
	}
	
	/**
	 * export_excel
	 *
	 * 导出Excel
	 * $titles 标题数组（必要是k-v形式的哈希表，key为字段名）
	 * $records 内容数组
	 * $filename 下载的文件名称
	 * $sheetname 工作表名称
	 */
	public static function export_excel($titles, $records, $filename = "data.xls", $sheetname = "Sheet1") {
		require_once Q::ini ( 'app_config/LIB_DIR' ) . '/PHPExcel.php';
		require_once Q::ini ( 'app_config/LIB_DIR' ) . '/PHPExcel/Writer/Excel5.php';
		$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
		if (! PHPExcel_Settings::setCacheStorageMethod ( $cacheMethod ))
			die ( 'CACHEING ERROR' );
		ini_set ( 'memory_limit', '2048M' );
		set_time_limit ( 600 );
		// 创建一个处理对象实例  
		$objExcel = new PHPExcel ();
		$objWriter = new PHPExcel_Writer_Excel5 ( $objExcel );
		$objActSheet = $objExcel->getActiveSheet ();
		$objActSheet->setTitle ( $sheetname );
		
		//设置表头
		$zm = ord ( 'A' );
		$za = '';
		foreach ( $titles as $title ) {
			$objActSheet->setCellValue ( $za.chr ( $zm ) . '1', $title );
			//表头加粗
			$objStyleA5 = $objActSheet->getStyle ( $za.chr ( $zm ) . '1' );
			$objFontA5 = $objStyleA5->getFont ();
			$objFontA5->setBold ( true );
			if (chr($zm) != 'Z') $zm++;
			else {
				$zm = ord('A');
				if (!$za) $za = 'A';
				else $za = chr(ord($za)+1);
			}
		}
		
		//内容
		foreach ( $records as $i => $rec ) {
			$zm = ord ( 'A' );
			$za = '';
			foreach ( $titles as $k => $v ) {
				$objActSheet->setCellValueExplicit ( $za.chr ( $zm ) . ($i + 2), $rec [$k], PHPExcel_Cell_DataType::TYPE_STRING );
				if (chr($zm) != 'Z') $zm++;
				else {
					$zm = ord('A');
					if (!$za) $za = 'A';
					else $za = chr(ord($za)+1);
				}
			}
		}
		
		//输出内容
		Helper_Util::add_dl_header ( $filename );
		
		$objWriter->save ( 'php://output' );
		die;
	}
	
	/**
	 * export_excel
	 *
	 * 导出Excel
	 * $titles 标题数组（必要是k-v形式的哈希表，key为字段名）
	 * $records 内容数组
	 * $filename 下载的文件名称
	 * $sheetname 工作表名称
	 */
	public static function export_excel_change($titles, $records, $filename = "data.xls", $sheetname = "Sheet1",$changeDate,$dateStyle) {
		require_once Q::ini ( 'app_config/LIB_DIR' ) . '/PHPExcel.php';
		require_once Q::ini ( 'app_config/LIB_DIR' ) . '/PHPExcel/Writer/Excel5.php';
		$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
		if (! PHPExcel_Settings::setCacheStorageMethod ( $cacheMethod ))
			die ( 'CACHEING ERROR' );
		ini_set ( 'memory_limit', '2048M' );
		set_time_limit ( 600 );
		// 创建一个处理对象实例  
		$objExcel = new PHPExcel ();
		$objWriter = new PHPExcel_Writer_Excel5 ( $objExcel );
		$objActSheet = $objExcel->getActiveSheet ();
		$objActSheet->setTitle ( $sheetname );
		
		//设置表头
		$zm = ord ( 'A' );
		foreach ( $titles as $title ) {
			$objActSheet->setCellValue ( chr ( $zm ) . '1', $title );
			//表头加粗
			$objStyleA5 = $objActSheet->getStyle ( chr ( $zm ++ ) . '1' );
			$objFontA5 = $objStyleA5->getFont ();
			$objFontA5->setBold ( true );
		}
		//内容
		foreach ( $records as $i => $rec ) {
			$zm = ord ( 'A' );
			foreach ( $titles as $k => $v ) {
				$val = $rec [$k];
				if(in_array($k, $changeDate)){
					//dump($k);
					$value = $val;
					switch ($k){
						case 'examdate':
							$val = date($dateStyle[$k],$value);
							continue;
						case 'isreplace':
							if ($value == 0)
								$val = "否";
							else if ($value == 2)
								$val = "免考免修";
							continue;
						case 'passed':
							$val = $value==0?"未通过":"通过";
							continue;
						case 'dingti':
							$val = $value==1?"是":"否";
							continue;
						default:
							$val = "录入数据出错";
							continue;
					}
					$value="";
				}
				
				$objActSheet->setCellValueExplicit ( chr ( $zm ++ ) . ($i + 2), $val, PHPExcel_Cell_DataType::TYPE_STRING );
				$val = "";
			}
		}
		
		//输出内容
		Helper_Util::add_dl_header ( $filename );
		
		$objWriter->save ( 'php://output' );
	}
	
	//同上 但titles字段从form中读取
	public static function export_form_excel($model, $records, $filename = "data.xls", $sheetname = "Sheet1", $titles_add = null) {
		$titles = array ();
		if ($model) {
			$formfile = Q::ini ( 'app_config/APP_DIR' ) . '/form/' . $model . '_form.yaml';
			$form = Helper_YAML::loadCached ( $formfile );
			foreach ( $form as $k => $v ) {
				if ($k == '~form')
					continue;
				if (empty ( $v ['_label'] ))
					continue;
				if (!empty($v['_noex'])) continue;
				if (! empty ( $v ['_exkey'] ))
					$k = $v ['_exkey'];
				$titles [$k] = $v ['_label'];
			}
		}
		if ($titles_add) {
			$titles += $titles_add;
		}
		Helper_Util::export_excel ( $titles, $records, $filename, $sheetname );
	}
	
	//同上 但titles字段从form中读取并且从yaml中去掉不需要的字段
	public static function export_form_excel_exceptarr($model, $records, $filename = "data.xls", $sheetname = "Sheet1", $titles_add = null, $arr = null) {
		$formfile = Q::ini ( 'app_config/APP_DIR' ) . '/form/' . $model . '_form.yaml';
		$form = Helper_YAML::loadCached ( $formfile );
		$titles = array ();
		foreach ( $form as $k => $v ) {
			if (! in_array ( $k, $arr )) {
				if ($k == '~form')
					continue;
				if (empty ( $v ['_label'] ))
					continue;
				if (!empty($v['_noex'])) continue;
				if (! empty ( $v ['_exkey'] ))
					$k = $v ['_exkey'];
				$titles [$k] = $v ['_label'];
			}
		}
		if ($titles_add) {
			$titles += $titles_add;
		}
		Helper_Util::export_excel ( $titles, $records, $filename, $sheetname );
	}
	
	static  function idcard_verify_number($idcard_base) {
		if (strlen ( $idcard_base ) != 17) {
			$this->showMsg ( "您输入的身份证位数不对，请您重新填写！！！", "" );
			return false;
		}
		//加权因子 
		$factor = array (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 );
		//校验码对应值 
		$verify_number_list = array ('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' );
		$checksum = 0;
		for($i = 0; $i < strlen ( $idcard_base ); $i ++) {
			$checksum += substr ( $idcard_base, $i, 1 ) * $factor [$i];
		}
		$mod = strtoupper ( $checksum % 11 );
		$verify_number = $verify_number_list [$mod];
		
		return $verify_number;
	}
	
	//将15位身份证升级到18位 
	static  function idcard_15to18($idcard) {
		if (strlen ( $idcard ) != 15) {
			$this->showMsg ( "您输入的身份证位数不对，请您重新填写！！！", "" );
			return false;
		} else {
			//如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码 
			if (array_search ( substr ( $idcard, 12, 3 ), array ('996', '997', '998', '999' ) ) != false) {
				$idcard = substr ( $idcard, 0, 6 ) . '18' . substr ( $idcard, 6, 9 );
			} else {
				$idcard = substr ( $idcard, 0, 6 ) . '19' . substr ( $idcard, 6, 9 );
			}
		}
		$idcard = $idcard . self::idcard_verify_number ( $idcard );
		return $idcard;
	}
	
	//18位身份证校验码有效性检查 
	static function idcard_checksum18($idcard) {
		if (strlen ( $idcard ) != 18) {
			return false;
		}
		$aCity = array (11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外" );
		//非法地区 
		if (! array_key_exists ( substr ( $idcard, 0, 2 ), $aCity )) {
			return false;
		}
		//验证生日 
		if (! checkdate ( substr ( $idcard, 10, 2 ), substr ( $idcard, 12, 2 ), substr ( $idcard, 6, 4 ) )) {
			return false;
		}
		$idcard_base = substr ( $idcard, 0, 17 );
		if (self::idcard_verify_number ( $idcard_base ) != strtoupper ( substr ( $idcard, 17, 1 ) )) {
			return false;
		} else {
			return true;
		}
	}

	static function mkdir($filename){
		if (file_exists($filename))return ;
		self::mkdir(dirname($filename));
		mkdir($filename);
	}
	//生成2011/12/26这种日期目录
	static function mk_date_dir($rootdir){
		$my_dir_Y = date('Y').DIRECTORY_SEPARATOR;
		$my_dir_m = date('m').DIRECTORY_SEPARATOR;
		$my_dir_d = date('d').DIRECTORY_SEPARATOR;
		self::mkdir($rootdir.$my_dir_Y);
		self::mkdir($rootdir.$my_dir_Y.$my_dir_m);
		self::mkdir($rootdir.$my_dir_Y.$my_dir_m.$my_dir_d);
		return $my_dir_Y.$my_dir_m.$my_dir_d;
	}
	//截取太长的标题，适用于utf8字符
	static function utfSubStr($str,$len,$suffix='...'){
		$theStr = $str;
		for ($i=0;$i<$len;$i++) {
			$temp_str = substr($str,0,1);
			if (ord($temp_str) > 127) {
				$i++;
				if ($i < $len) {
					$new_str[]	= substr($str,0,3);
					$str		= substr($str,3);
				}
			} else {
				$new_str[]	= substr($str,0,1);
				$str		= substr($str,1);
			}
		}
		if($theStr == join($new_str)){
			return $theStr;
		} else {
			return join($new_str).$suffix;
		}
	}
	//随机产生字符串，$len为长度
	static function str_random($len = 4){
		$consts = 'bcdfghjkmnpqrstwxyz';
		$vowels = 'aei23456789';
		for ($x = 0; $x < 6; $x++)
		{
			$const[$x] = substr($consts, mt_rand(0,strlen($consts)-1),1);
			$vow[$x] = substr($vowels, mt_rand(0,strlen($vowels)-1),1);
		}
		$radomstring = $const[0].$const[2] . $vow[0] .$const[2] . $const[1] . $vow[1] . $const[3]. $const[4] . $vow[3] . $const[4];
		$radomstring = substr($radomstring,0,$len);
		return $radomstring;
	}

	//获取对应字段的数组
	static function getCols($ary) {
		$cols = array_slice(func_get_args(), 1);
		$ret = array();
		foreach ($ary as $row) {
			$obj = array();
			foreach ($cols as $col) {
				$obj[$col] = $row[$col];
			}
			$ret[] = $obj;
		}
		return $ret;
	}
	//得到当前页的url
	static function str_current_url(){
		if($_SERVER['SERVER_PORT'] == '80'){
			return $_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
		}else{
			return $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER["REQUEST_URI"];
		}
	}

	//获取对象的Array（不带自定义属性）
	static function toArray($rec) {
		$fields = $rec->meta()->table_meta;
		$data = $rec->toArray(0);
		$data2 = array();
		foreach ($data as $k=>$v) {
			if (isset($fields[$k]))
				$data2[$k] = $v;
		}
		return $data2;
	}

	//soap news推送至mynep
	static function soap_addnews($news) {
		return;
		include_once Q::ini('app_config/ROOT_DIR').'/_code/lib/nusoap/nusoap.php';
		//$client = new soapclient('http://10.82.97.201:8080/svn/jibo_mynep/index/newsapi');
		$client = new soapclient('http://work.myweb/jibo_mynep/index/newsapi');
		$result = $client->call('addNews', array(
			'site_id' => 4,
			'newsid' => $news->id(),
			'type_id' => $news->type_id,
			'title' => $news->title,
			'source' => $news->source,
			'author' => $news->author,
			'content' => $news->content,
			'release_date' => $news->release_date,
		));
	}
}
